package com.wlx.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wlx.auth.domain.PortalUser;
import com.wlx.auth.mapper.PortalUserMapper;
import com.wlx.auth.po.UserExt;
import com.wlx.auth.service.PortalUserService;
import com.wlx.common.core.enums.UserStatus;
import com.wlx.common.core.exception.BaseException;
import com.wlx.common.core.exception.CustomException;
import com.wlx.common.core.utils.ServletUtils;
import com.wlx.common.core.utils.StringUtils;
import com.wlx.common.core.utils.ip.IpUtils;
import com.wlx.common.mongodb.MongoDTO;
import com.wlx.common.mongodb.MongoDbResult;
import com.wlx.common.mongodb.MongoLike;
import com.wlx.common.mongodb.MongoQuery;
import com.wlx.system.api.model.CustomLoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 用户 业务层处理
 *
 * @author wlx
 */
@Service
public class PortalUserServiceImpl extends BaseServiceImpl implements PortalUserService {
    private static final Logger log = LoggerFactory.getLogger(PortalUserServiceImpl.class);

    @Autowired
    private PortalUserMapper userMapper;


    @Override
    protected String getCollectionName() {
        return "portalUser";
    }
    /////////////////////////mysql+mongodb方式存储//////////////////////////

    @Transactional(rollbackFor = CustomException.class)
    public CustomLoginUser phoneLogin1(CustomLoginUser customLoginUser) {
        if (StringUtils.isBlank(customLoginUser.getPhone())) {
            throw new BaseException("手机号必须填写");
        }

        PortalUser user = userMapper.selectUserByPhone(customLoginUser.getAppId(), customLoginUser.getPhone());
        if (StringUtils.isNull(user)) {
            throw new BaseException("登录用户手机号：" + customLoginUser.getPhone() + " 不存在");
        }

        user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        user.setLoginTime(new Date());
        userMapper.updateById(user);

        //获取用户其他对应不同业务的扩展信息
        MongoQuery mongoQuery = new MongoQuery();
        mongoQuery.setKey("userUuid");
        mongoQuery.setValue(user.getUuid());
        List<MongoQuery> queryParams = new ArrayList<>();
        queryParams.add(mongoQuery);
        JSONObject userExt = mongoDbUtil.queryOne(getCollectionName(), queryParams, JSONObject.class);

        CustomLoginUser userInfo = new CustomLoginUser();
        userInfo.setUserUuid(user.getUuid());
        userInfo.setLoginType(customLoginUser.getLoginType());
        BeanUtils.copyProperties(user, userInfo);
        if (StringUtils.isNotNull(userExt)) {
            userExt.remove("_id");
            userInfo.setExtData(userExt);
        }
        userInfo.setPassword(null);
        return userInfo;
    }

    @Transactional(rollbackFor = CustomException.class)
    public CustomLoginUser phoneRegister1(CustomLoginUser customLoginUser) {
        if (StringUtils.isBlank(customLoginUser.getPhone())) {
            throw new BaseException("手机号必须填写");
        }

        PortalUser user = userMapper.selectUserByPhone(customLoginUser.getAppId(), customLoginUser.getPhone());
        if (StringUtils.isNotNull(user)) {
            throw new BaseException("注册用户手机号：" + customLoginUser.getPhone() + " 已存在");
        }

        //处理必要数据与扩展数据
        PortalUser targetUser = new PortalUser();
        BeanUtils.copyProperties(customLoginUser, targetUser);
        targetUser.init();
        targetUser.setRegisterIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        targetUser.setRegisterTime(new Date());

        user.setLoginIp(targetUser.getRegisterIp());
        user.setLoginTime(targetUser.getRegisterTime());

        if (StringUtils.isBlank(targetUser.getNickname())) {
            targetUser.setNickname(targetUser.getPhone());
        }

        userMapper.insert(targetUser);

        JSONObject extData = customLoginUser.getExtData();
        if (StringUtils.isNotNull(extData)) {
            extData.put("userUuid", targetUser.getUuid());

            UserExt userExt = new UserExt();
            userExt.setUserUuid(targetUser.getUuid());
            userExt.setExtJson(extData);
            List<JSONObject> userExts = new ArrayList<>();
            userExts.add(extData);
            mongoDbUtil.insertDocument(getCollectionName(), userExts);

            extData.remove("_id");
        }

        //获取用户其他对应不同业务的扩展信息
        CustomLoginUser userInfo = new CustomLoginUser();
        userInfo.setUserUuid(targetUser.getUuid());
        userInfo.setLoginType(customLoginUser.getLoginType());
        BeanUtils.copyProperties(targetUser, userInfo);
        userInfo.setExtData(extData);
        return userInfo;
    }
    ///////////////////////////////////////////////////

    /////////////////////////mongodb单方式存储//////////////////////////

    @Override
    public CustomLoginUser phoneLogin(CustomLoginUser customLoginUser) {
        if (StringUtils.isBlank(customLoginUser.getPhone())) {
            throw new BaseException("手机号必须填写");
        }
        List<MongoQuery> mongoQueries = new ArrayList<>();
        MongoQuery mongoQuery = new MongoQuery();
        mongoQuery.setKey("appId");
        mongoQuery.setValue(customLoginUser.getAppId());
        mongoQueries.add(mongoQuery);
        mongoQuery = new MongoQuery();
        mongoQuery.setKey("phone");
        mongoQuery.setValue(customLoginUser.getPhone());
        mongoQueries.add(mongoQuery);
        JSONObject jsonObject = mongoDbUtil.queryOne(getCollectionName(), mongoQueries, JSONObject.class);
        if (StringUtils.isNull(jsonObject)) {
            throw new BaseException("登录用户手机号：" + customLoginUser.getPhone() + " 不存在");
        }
        String status = jsonObject.getString("status");
        if (UserStatus.DELETED.getCode().equals(status)) {
            throw new BaseException("对不起，您的账号：" + customLoginUser.getPhone() + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(status)) {
            throw new BaseException("对不起，您的账号：" + customLoginUser.getPhone() + " 已停用");
        }

        jsonObject.put("loginIp", IpUtils.getIpAddr(ServletUtils.getRequest()));
        jsonObject.put("loginTime", new Date());
        mongoDbUtil.updateOne(getCollectionName(), "uuid", jsonObject.getString("uuid"), jsonObject.getInnerMap());

        //获取用户其他对应不同业务的扩展信息
        CustomLoginUser userInfo = new CustomLoginUser();
        userInfo.setUserUuid(jsonObject.getString("uuid"));
        userInfo.setLoginType(customLoginUser.getLoginType());
        userInfo.setExtData(jsonObject);
        return userInfo;
    }

    @Override
    public CustomLoginUser phoneRegister(CustomLoginUser customLoginUser) {
        if (StringUtils.isBlank(customLoginUser.getPhone())) {
            throw new BaseException("手机号必须填写");
        }

        List<MongoQuery> mongoQueries = new ArrayList<>();
        MongoQuery mongoQuery = new MongoQuery();
        mongoQuery.setKey("appId");
        mongoQuery.setValue(customLoginUser.getAppId());
        mongoQueries.add(mongoQuery);

        mongoQuery = new MongoQuery();
        mongoQuery.setKey("phone");
        mongoQuery.setValue(customLoginUser.getPhone());
        mongoQueries.add(mongoQuery);
        JSONObject jsonObject = mongoDbUtil.queryOne(getCollectionName(), mongoQueries, JSONObject.class);

        if (StringUtils.isNotNull(jsonObject)) {
            throw new BaseException("注册用户手机号：" + customLoginUser.getPhone() + " 已存在");
        }

        //处理必要数据与扩展数据
        PortalUser targetUser = new PortalUser();
        BeanUtils.copyProperties(customLoginUser, targetUser);
        targetUser.init();
        targetUser.setRegisterIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        targetUser.setLoginIp(targetUser.getRegisterIp());
        if (StringUtils.isBlank(targetUser.getNickname())) {
            targetUser.setNickname(targetUser.getPhone());
        }
        String s = JSONObject.toJSONString(targetUser);
        JSONObject object = JSONObject.parseObject(s);
        JSONObject extData = customLoginUser.getExtData();
        if (StringUtils.isNotNull(extData)) {
            object.putAll(extData);
        }
        Date date = new Date();
        object.put("registerTime", date);
        object.put("loginTime", date);
        List<JSONObject> userExts = new ArrayList<>();
        userExts.add(object);
        mongoDbUtil.insertDocument(getCollectionName(), userExts);
        object.remove("_id");

        //获取用户其他对应不同业务的扩展信息
        CustomLoginUser userInfo = new CustomLoginUser();
        userInfo.setUserUuid(targetUser.getUuid());
        userInfo.setLoginType(customLoginUser.getLoginType());
        userInfo.setExtData(object);
        return userInfo;
    }

    @Override
    public MongoDbResult queryPageByParam(MongoDTO mongoDTO) {
        List<MongoLike> queryParams = mongoDTO.getQueryParams();
        Map<String, String> sortParams = mongoDTO.getSortParams();
        int current = mongoDTO.getCurrent();
        int size = mongoDTO.getSize();
        MongoDbResult mongoDbResult = mongoDbUtil.queryByParameterLike(getCollectionName(), queryParams, sortParams, current, size, JSONObject.class);
        return mongoDbResult;
    }

    @Override
    public JSONObject searchOne(String userUuid) {
        List<MongoQuery> mongoQueries = new ArrayList<>();
        MongoQuery mongoQuery = new MongoQuery();
        mongoQuery.setKey("uuid");
        mongoQuery.setValue(userUuid);
        mongoQueries.add(mongoQuery);
        JSONObject jsonObject = mongoDbUtil.queryOne(getCollectionName(), mongoQueries, JSONObject.class);
        return jsonObject;
    }

    @Override
    public void updateOne(String userUuid, String status) {
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("status", status);
        mongoDbUtil.updateOne(getCollectionName(), "uuid", userUuid, updateMap);
    }

    @Override
    public void deleteOne(String userUuid) {
        List<Object> ids = new ArrayList<>();
        ids.add(userUuid);
        mongoDbUtil.deleteDocument(getCollectionName(), "uuid", ids);
    }

    @Override
    public List<JSONObject> queryAggregate(String uuid) {
        return mongoDbUtil.queryAggregate(getCollectionName(), uuid);
    }

    @Override
    public List<JSONObject> queryTest() {
        return mongoDbUtil.test(getCollectionName());
    }
}
